<template>
  <x-sub-page class="rectify-inform-add" :content="title" @goBack="handleBack">
    <el-form :model="params" :rules="rules" ref="params" class="form-inline" label-position="top">
      <div class="form-components">
        <div class="panl-title">
          <span>基础信息</span>
        </div>

        <el-row :gutter="20">
          <x-col>
            <el-form-item :label="$t('shipment.form.consignor')" prop="consignor">
              <el-input v-model="params.consignor" placeholder="请输入" style="width: 100%" maxlength="20"></el-input>
            </el-form-item>
          </x-col>
          <x-col>
            <el-form-item :label="$t('shipment.form.consignorPhone')" prop="consignorPhone">
              <el-input
                v-model="params.consignorPhone"
                placeholder="请输入"
                style="width: 100%"
                maxlength="20"
              ></el-input>
            </el-form-item>
          </x-col>
          <x-col>
            <el-form-item :label="$t('shipment.form.deliveryMethod')" prop="deliveryMethod">
              <x-select
                placeholder="请选择"
                v-model="params.deliveryMethod"
                :options="dictOptions['srm_delivery_note.delivery_method']"
                style="width: 100%"
              />
            </el-form-item>
          </x-col>
          <!-- 自主配送 -->
          <template v-if="params.deliveryMethod === 'self'">
            <x-col>
              <el-form-item :label="$t('shipment.form.shipper')" prop="shipper" key="shipper">
                <el-input v-model="params.shipper" placeholder="请输入" style="width: 100%" maxlength="20"></el-input>
              </el-form-item>
            </x-col>
            <x-col>
              <el-form-item :label="$t('shipment.form.shipperPhone')" prop="shipperPhone" key="shipperPhone">
                <el-input
                  v-model="params.shipperPhone"
                  placeholder="请输入"
                  style="width: 100%"
                  maxlength="20"
                ></el-input>
              </el-form-item>
            </x-col>
          </template>
          <template v-else>
            <!-- 物流配送 -->
            <x-col>
              <el-form-item
                :label="$t('shipment.form.logisticalCompany')"
                prop="logisticalCompany"
                key="logisticalCompany"
              >
                <x-select
                  placeholder="请选择"
                  v-model="params.logisticalCompany"
                  :options="dictOptions['srm_delivery_note.logistical_company']"
                  style="width: 100%"
                />
              </el-form-item>
            </x-col>
            <x-col>
              <el-form-item
                :label="$t('shipment.form.logisticalNumber')"
                prop="logisticalNumber"
                key="logisticalNumber"
              >
                <el-input
                  v-model="params.logisticalNumber"
                  placeholder="请输入"
                  style="width: 100%"
                  maxlength="20"
                ></el-input>
              </el-form-item>
            </x-col>
          </template>
          <x-col>
            <el-form-item :label="$t('shipment.form.deliveryDate')" prop="deliveryDate">
              <el-date-picker
                v-model="params.deliveryDate"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="'请输入'"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </x-col>
          <x-col>
            <el-form-item :label="$t('shipment.form.arrivalDate')" prop="arrivalDate">
              <el-date-picker
                v-model="params.arrivalDate"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="'请输入'"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </x-col>
          <x-col :span="24">
            <el-form-item :label="'附件'" prop="file">
              <x-upload
                ref="fileUpload"
                :fileSize="30"
                :span="6"
                :isFileRemark="false"
                :edit-flag="true"
                :limit="9"
                :old-file-list="params.deliveryNoteFileList"
                :file-type="['jpg', 'jpeg', 'png', 'ppt', 'pptx', 'pdf', 'xls', 'xlsx', 'doc', 'docx']"
                :tips="'支持上传PPT/PDF/EXCEL/WORD/PNG/JPG形式文件, 最多9个, 附件大小不超过30MB.'"
              >
              </x-upload>
            </el-form-item>
          </x-col>
        </el-row>
      </div>

      <div class="form-components">
        <div class="panl-title">
          <span>送货物料明细</span>
        </div>
      </div>
      <el-row type="flex" class="tools" justify="space-between">
        <el-col :span="20" class="btnStyle">
          <el-button type="primary" @click="handlePurchase"> {{ '来源采购订单' }}</el-button>
          <el-button @click="handleBatchDel" type="danger"> {{ $t('common.batchDelete') }}</el-button>
        </el-col>
      </el-row>
      <x-table
        ref="tableCom"
        :isPagination="false"
        :data-source="params.deliveryNoteDetailList"
        :row-key="'id'"
        @on-selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="(item, index) in columns"
          :key="index"
          :prop="item.prop"
          :fixed="item.fixed"
          :show-overflow-tooltip="true"
          :width="item.width"
          :min-width="item.minWidth || '-'"
          :label="item.label"
          :sortable="'custom'"
        >
          <template slot="header">
            <span class="headerRequire" v-if="item.prop === 'deliveryQuantity'">{{
              $t('shipment.column.deliveryQuantity')
            }}</span>
            <span v-else>{{ item.label }}</span>
          </template>
          <template #default="scope">
            <el-form-item
              v-if="item.prop === 'deliveryQuantity'"
              :prop="`deliveryNoteDetailList.${scope.$index}.${['deliveryQuantity']}`"
              :rules="rules['deliveryQuantity']"
            >
              <el-input-number
                v-if="isDetail"
                v-model="scope.row.deliveryQuantity"
                placeholder="请输入"
                size="small"
                :min="0"
                :max="99999999"
                :precision="0"
                :controls="false"
              ></el-input-number>
              <span v-else>{{ scope.row.deliveryQuantity }}</span>
            </el-form-item>
            <span v-else-if="item.prop === 'deliveryDate'">{{ replaceDateTime(scope.row[item.prop]) }}</span>
            <span v-else-if="item.prop === 'materialUnit'">{{selectDictLabel(dictOptions['srm_material.material_unit'], scope.row[item.prop])}}</span>
            <span v-else>{{ scope.row[item.prop] | emptyVal }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-link type="danger" :underline="false" @click="delRow(scope.row.id)">删除</el-link>
          </template>
        </el-table-column>
      </x-table>
    </el-form>

    <fixed-btn-area v-if="isDetail">
      <el-button @click="handleBack"> {{ $t('common.cancel') }} </el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading"> {{ '提交' }} </el-button>
    </fixed-btn-area>
    <purchase-order-dialog
      ref="purchaseOrderDialog"
      :multiple="true"
      @on-confirm="confirmSubmit"
    ></purchase-order-dialog>
  </x-sub-page>
</template>
<script>
  import { formatSubmitFiles, QueryDictMixin, throttle, replaceDateTime,selectDictLabel } from '@package/utils'
  import { mapState, mapActions } from 'pinia'
  import { detailColumns } from '@/modules/shipment/config/wholeOrderReceipt.js'
  import {
    apiDeliveryNoteAdd,
    apiDeliveryNoteUpdate,
    apiGetDeliveryDetail
  } from '@/modules/shipment/api/receivingManagement.js'
  import { EnumApiCode } from '../../../../../../globalEnum.js'
  import PurchaseOrderDialog from '../components/PurchaseOrderDialog.vue'
  import { pinias } from '@/common/pinia'

  const { login } = pinias
  export default {
    name: 'DeliverAdd',
    components: { PurchaseOrderDialog },
    mixins: [QueryDictMixin],
    inject: ['closePages'],
    data() {
      return {
        columns: detailColumns,
        id: '',
        params: {
          consignor: '',
          consignorPhone: '',
          deliveryMethod: '',
          shipper: '',
          shipperPhone: null,
          deliveryDate: null,
          logisticalCompany: null,
          logisticalNumber: null,
          arrivalDate: '',
          deliveryQuantity: '', // 本次期待
          deliveryNoteDetailList: [],
          deliveryNoteFileList: []
        },
        isDetail: true,
        selectData: [],
        rules: {
          consignor: [{ required: true, message: '请输入发货人', trigger: 'blur' }],
          consignorPhone: [{ required: true, message: '请输入发货人联系人方式', trigger: 'blur' }],
          deliveryMethod: [{ required: true, message: '请选择送货方式', trigger: 'blur' }],
          shipper: [{ required: true, message: '送货人', trigger: ['change', 'blur'] }],
          shipperPhone: [{ required: true, message: '请输入送货人联系人方式', trigger: ['change', 'blur'] }],
          logisticalCompany: [{ required: true, message: '请选择物流公司', trigger: ['change', 'blur'] }],
          logisticalNumber: [{ required: true, message: '请输入物流单号', trigger: ['change', 'blur'] }],
          arrivalDate: [{ required: true, message: '请选择预计到达日期', trigger: 'blur' }],
          deliveryDate: [{ required: true, message: '请选择预计发货日期', trigger: 'blur' }],
          deliveryQuantity: [{ required: true, message: '请输入', trigger: 'blur' }]
        },
        loading: false,
        srmDictKeys: ['srm_delivery_note.delivery_method', 'srm_delivery_note.logistical_company','srm_material.material_unit'],
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 86_400_000
          }
        }
      }
    },
    computed: {
      title() {
        return `${this.id ? '编辑' : '新建'}`
      }
    },
    created() {
      this.id = this.$route.query.id
      this.initDictConfig()
      this.id && this.init()
    },
    methods: {
      replaceDateTime,
      selectDictLabel,
      async init() {
        const { data, code } = await apiGetDeliveryDetail(this.id)
        if (code === EnumApiCode.Success) {
          this.params = { ...data }
          // this.params.deliveryNoteDetailList?.forEach(item=>{

          //   item.deliveryQuantityLast=item.deliveryQuantity
          // })
        }
      },
      // 多行选中
      handleSelectionChange(rows) {
        this.selectData = rows
      },
      // 批量删除
      handleBatchDel() {
        if (this.selectData.length === 0) {
          this.$message.error('请至少选择一条数据')
          return
        }
        this.delRow()
      },
      //    删除
      delRow(i) {
        const rowIndexs = i
          ? [i]
          : this.selectData.map((el) => {
              return el.id
            })
        this.$confirm('是否删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.params.deliveryNoteDetailList = this.params.deliveryNoteDetailList.filter((item) => {
            return !rowIndexs.includes(item.id)
          })
        })
      },
      handlePurchase() {
        this.$refs.purchaseOrderDialog.show()
      },
      // 确定来源采购订单
      confirmSubmit(arr) {
        const ids = this.params.deliveryNoteDetailList.map((el) => {
          return el.id
        })
        arr.forEach((item) => {
          if (!ids.includes(item.id)) {
            this.params.deliveryNoteDetailList.push({
              ...item,
              orderDetailId: item.id,
              deliveryQuantity: item.remainingQuantity
            })
          }
        })
      },
      handleBack() {
        this.handleCancel()
      },
      handleCancel() {
        this.$router.go(-1)
        this.closePages()
      },
      getParams(action) {
        return {
          ...this.params,
          supplierId: this.params.deliveryNoteDetailList[0].supplierId,
          supplierName: this.params.deliveryNoteDetailList[0].supplierName,
          deliveryDate: `${this.params.deliveryDate} 23:59:59`,
          arrivalDate: `${this.params.arrivalDate} 23:59:59`,
          deliveryNoteFileList: formatSubmitFiles(this.$refs.fileUpload.fileList),
          action
        }
      },
      handleSubmit: throttle(function (action) {
        if (this.params.deliveryNoteDetailList.length == 0) {
          this.$message.error('请至少选择一条采购订单')
          return
        }
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            const param = this.getParams(action)
            try {
              this.loading = true
              const { code } = this.params.id ? await apiDeliveryNoteUpdate(param) : await apiDeliveryNoteAdd(param)
              if (code === EnumApiCode.Success) {
                this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
                this.handleCancel()
              }
            } finally {
              this.loading = false
            }
          } else {
            return false
          }
        })
      }, 1000)
    }
  }
</script>
<style lang="scss" scoped>
  .rectify-inform-add {
    overflow: auto;
    .form-inline {
      width: 100%;
      height: calc(100% - 71px);
      padding: 20px;
      overflow-y: auto;
      box-sizing: border-box;
    }
    .panl-title {
      height: 45px;
      // margin: 0 16px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ededed;
      margin-bottom: 16px;
      span {
        display: inline-block;
        height: 22px;
        line-height: 22px;
        color: #171c26;
        border-left: 2px solid #4474f6;
        padding-left: 12px;
        font-size: 16px;
        font-weight: 700;
      }
    }
    .btnStyle {
      margin-bottom: 16px;
    }
    ::v-deep .el-table__row .el-form-item {
      margin-bottom: 0;
    }
    ::v-deep .el-table__row .el-form-item__error {
      padding-top: 0;
    }
    ::v-deep .el-table__row .el-form-item__content {
      line-height: 32px;
    }
    .headerRequire:before {
      content: '*';
      color: #f56c6c;
      margin-right: 4px;
    }
    ::v-deep .el-table__cell {
      .el-input-number--small {
        width: 100%;
        height: 28px;
        .el-input--small {
          height: inherit;

          input {
            height: inherit;
            width: 100%;
            text-align: left;
          }
        }
      }
    }
  }
</style>
